package com.ido.otaclient.home;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;

import com.ido.otaclient.DeviceManagerModel;
import com.ido.otaclient.R;
import com.ido.otaclient.base.BaseFragment;
import com.ido.otaclient.base.IDLog;
import com.ido.otaclient.dialog.WaitingDialog;
import com.ido.otaclient.dialog.WhiteConfirmDialog;
import com.ido.otaclient.env.AppEnv;
import com.ido.otaclient.module.Device;
import com.ido.otaclient.module.Veneer;
import com.ido.otaclient.util.ResourceUtil;
import com.ido.otaclient.util.ToastUtils;



import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2020-02-11 17:13
 * @description
 */
public class HomeFragment extends BaseFragment implements HomeContract.View{
    private static final String TAG = "HomeFragment";
    /**
     * 升级配置
     */
    @BindView(R.id.btn_update_config)
    Button mbtnUpdateConfig;
    /**
     * 单板数量
     */
    @BindView(R.id.tv_veneer_account)
    TextView mTvVeneerCount;
    /**
     * 设备数量
     */
    @BindView(R.id.tv_device_account)
    TextView mTvDeviceCount;
    /**
     * 开始任务
     */
    @BindView(R.id.btn_start)
    Button mBtnStart;
    /**
     * 升级名称
     */
    @BindView(R.id.tv_task_name)
    TextView mTvTvTaskName;
    /**
     * 未配置首次进来的时候
     */
    @BindView(R.id.tv_start_config)
    TextView mTvStartConfig;
    /**
     * 升级类型
     */
    @BindView(R.id.ll_upload_type)
    LinearLayout mLluploadType;
    /**
     * 升级类型的值
     */
    @BindView(R.id.tv_upload_type_value)
    TextView mtvUploadTypeValue;
    /**
     * 升级平台
     */
    @BindView(R.id.ll_upload_platform)
    LinearLayout mLlUploadPlatform;
    /**
     * 平台名称
     */
    @BindView(R.id.tv_ble_platform_value)
    TextView mTvBlePlatformValue;
    /**
     * 普通固件
     */
    @BindView(R.id.ll_firmware_normal)
    LinearLayout mLlFirmsareNormal;
    /**
     * 普通固件名称
     */
    @BindView(R.id.tv_firmware_normal_name)
    TextView mTvFirmwareNormalName;
    /**
     * 普通固件版本
     */
    @BindView(R.id.tv_firmware_normal_version_value)
    TextView mTvFirmwareNormalVersionValue;
    /**
     * 蓝牙固件
     */
    @BindView(R.id.ll_bootloader)
    LinearLayout mLlBootloader;
    /**
     * 蓝牙固件名称
     */
    @BindView(R.id.tv_bootloader_value)
    TextView mTvBootloaderValue;
    /**
     * 蓝牙固件版本
     */
    @BindView(R.id.tv_bootloader_version_value)
    TextView mTvBootloaderVersionValue;
    /**
     * 特殊固件
     */
    @BindView(R.id.ll_firmware_special)
    LinearLayout mLlFirmwareSpecial;
    /**
     * 升级中的数量
     */
    @BindView(R.id.tv_upgrade_count)
    TextView mTvUpgradeCount;
    /**
     * 升级成功的数量
     */
    @BindView(R.id.tv_success_count)
    TextView mTvSuccessCount;
    /**
     * 失败的数量
     */
    @BindView(R.id.tv_fail_count)
    TextView mTvFailCount;
    /**
     * 升级类型
     */
    @BindView(R.id.tv_upload_type)
    TextView mTvUploadType;
    /**
     * 升级平台
     */
    @BindView(R.id.tv_ble_platform)
    TextView mTvBlePlatform;
    /**
     * 设备id
     */
    @BindView(R.id.tv_device_id)
    TextView mTvDeviceId;
    /**
     * 特殊固件名称
     */
    @BindView(R.id.tv_firmware_special_name)
    TextView mTvFirmwareSpecialName;
    /**
     * 特殊固件值
     */
    @BindView(R.id.tv_firmware_specialversion_value)
    TextView mTvFirmwareSpecialversionValue;
    /**
     * 字库文件
     */
    @BindView(R.id.ll_firmware_font)
    LinearLayout mLlFirmwareFont;
    /**
     * 字库固件
     */
    @BindView(R.id.tv_firmware_font_name)
    TextView mTvFirmwareFontName;
    /**
     * 字库文件版本
     */
    @BindView(R.id.tv_firmware_font_version_value)
    TextView mTvFirmwareFontVersionValue;
    /**
     * 新固件的名称
     */
    @BindView(R.id.ll_firmware_new)
    LinearLayout mLlFirmwareNew;
    @BindView(R.id.tv_firmware_new_name)
    TextView mTvFirmwareNewName;
    @BindView(R.id.tv_firmware_new_version_value)
    TextView mTvFirmwareNewVersionValue;

    /**
     * 开始任务的loading
     */
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;

    /**
     * 查找成功
     */
    @BindView(R.id.btn_search_success)
    Button mBtnSearchSuccess;
    /**
     * 配置监听
     */
    private OnItemListener mOnItemListener;

    /**
     * 设备列表
     */
    private List<Device> mDeviceList = new ArrayList<>();

    /**
     * 单板数量
     */
    private List<Veneer> mVeneerList = new ArrayList<>();

    /**
     * 主界面之间的数据传递
     */
    private DeviceManagerModel mDeviceManagerModel;

    private HomeContract.Presenter mPresenter;

    /**
     * tts 对象
     */
    private TextToSpeech mTextToSpeech;

    /**
     * 任务名称
     */
    public void startTask(String taskName){
        mPresenter.getConfigInfo();
        mPresenter.toStartTask(mVeneerList,taskName);
    }

    public void setOnItemListener(OnItemListener onItemListener) {
        this.mOnItemListener = onItemListener;
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home;
    }

    @Override
    public void onViewCreatedTask(View view, Bundle savedInstanceState) {
        super.onViewCreatedTask(view, savedInstanceState);

        initData();
        initListener();
    }


    @Override
    public void setPresenter(@NonNull HomeContract.Presenter presenter) {
        mPresenter = presenter;
    }

    /**
     * 设置侧换栏回调
     */
    public interface OnItemListener {
        void onConfig(boolean isConfig,boolean mIsUpgradeComplete);
    }

    public static HomeFragment newInstance() {

        Bundle args = new Bundle();

        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }


    private void initData() {

        mPresenter = new HomePresenter(this);

        mDeviceManagerModel = ViewModelProviders.of(getActivity()).get(DeviceManagerModel.class);

        mDeviceManagerModel.getVeneerModelLiveData().observe(getActivity(),veneerList -> {
            setVeneerList(veneerList);
        });

        mDeviceManagerModel.getDeviceModelLiveData().observe(getActivity(),devices -> {
            setDeviceList(devices);
        });

        mDeviceManagerModel.getPlayTime().observe(getActivity(), time -> {
            getVeneerStatus();
        });
        mTextToSpeech = new TextToSpeech(AppEnv.instance().getContext(), status -> {
            //todo 是否要处理播放状态
        });
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        mTextToSpeech.setPitch(1.0f);
        // 设置语速
        mTextToSpeech.setSpeechRate(1.0f);

        showStartConfig(true);

    }


    /**
     * 设置设备的信息
     * @param devices
     */
    private void setDeviceList(List<Device> devices) {
       IDLog.d(TAG, "setDeviceList: " +devices.size());
        if(mDeviceList != null){
            mDeviceList.clear();
            mDeviceList.addAll(devices);
        }
        if(mDeviceList == null || mDeviceList.size() == 0){
            mTvDeviceCount.setTextColor(ResourceUtil.getResources().getColor(R.color.com_color_red));
            mTvDeviceCount.setText(String.valueOf(0));
        }else {
            mTvDeviceCount.setText(String.valueOf(mDeviceList.size()));
            mTvDeviceCount.setTextColor(ResourceUtil.getColor(R.color.com_color_black_text));
        }
        mPresenter.showDeviceList(mDeviceList);
    }

    /**
     * 设置新的单板集合
     * @param veneerList
     */
    private void setVeneerList(List<Veneer> veneerList) {
        IDLog.d(TAG, "setVeneerList: " +veneerList);
        if(mVeneerList != null){
            IDLog.d(TAG, "setVeneerList: " + "不为空");
            mVeneerList.clear();
        }else {
            IDLog.d(TAG, "setVeneerList: " + "为空");
            mVeneerList = new ArrayList<>();
        }
        mVeneerList.addAll(veneerList);
        int countEffect = mVeneerList.size();
        for(Veneer veneer : mVeneerList){
            if(veneer.getFailConnectCount() >= 3){
                countEffect--;
            }
        }
        if(countEffect == 0){
            showProgress(false);
            mTvVeneerCount.setTextColor(ResourceUtil.getColor(R.color.com_color_red));
            mTvVeneerCount.setText(String.valueOf(0));
        }else {
            mTvVeneerCount.setText(String.valueOf(veneerList.size()));
            mTvVeneerCount.setTextColor(ResourceUtil.getColor(R.color.com_color_black_text));
        }
    }


    @Override
    public void onStartTask() {
        super.onStartTask();
        //mPresenter.getConfigInfo();
        //刷新设备数据和单板数据
        showDeviceInfo();
    }

    /**
     * 显示连接设备信息
     */
    private void showDeviceInfo() {
        /*IDLog.d(TAG, "showDeviceInfo: " + mDeviceList.size());
        IDLog.d(TAG, "showDeviceInfo: " + mVeneerList.size());*/
        mDeviceList = mDeviceManagerModel.getDeviceModelLiveData().getValue();
        List<Device> deviceList = new ArrayList<>();
        if(mDeviceList != null){
            deviceList.addAll(mDeviceList);
            setDeviceList(deviceList);
            for(int i = 0;i < mDeviceList.size();i++){
                IDLog.d(TAG, "showDeviceInfo: " + mDeviceList.get(i).toString());
            }
        }else {
            mDeviceList = new ArrayList<>();
        }

        /**
         * 得到设备信息显示
         */
        mVeneerList = mDeviceManagerModel.getVeneerModelLiveData().getValue();
        List<Veneer> veneerList = new ArrayList<>();
        if(mVeneerList != null){
            IDLog.d(TAG, "showDeviceInfo: ++" + mVeneerList.size());
            veneerList.addAll(mVeneerList);
            setVeneerList(veneerList);
            sendVeneerList(veneerList);
            for(int i = 0;i < mVeneerList.size();i++){
                IDLog.d(TAG, "showDeviceInfo: " + mVeneerList.get(i).toString());
            }
        }
    }

    @Override
    public void onResumeTask() {
        super.onResumeTask();
        //getConfigInfo();
        IDLog.d(TAG, "onResumeTask: ");
    }

    private void getVeneerStatus() {
        mPresenter.getVeneerStatus(mVeneerList,mDeviceList);
    }



    private void initListener() {

    }

    @OnClick(R.id.btn_update_config)
    public void toConfig(View view) {
        //todo 升级过程中弹出取消框
        /*if (mOnItemListener != null) {
            mOnItemListener.onConfig(true);
        }*/
        mPresenter.confirmConfig(true);
    }

    @OnClick(R.id.btn_start)
    public void toStart(View view) {
        // 1、获取有效的单板ip
        // 2、通过有效的单板ip获取有效的设备
        // 3、将需要升级的设备分配给有效的单板ip进行升级
        Log.d(TAG, "toStart: ");
        mPresenter.confirmConfig(false);
        //测试接口返回
        //String ip = "http://192.168.1.4:5000/test";
        //testConnect(ip);
    }


    @OnClick(R.id.btn_search_success)
    public void toSearchSuccess(View view){
        mPresenter.searchTask(mVeneerList,mDeviceList);
    }

    @Override
    public void showTaskName(boolean isVisible) {
        mTvTvTaskName.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setTaskName(String taskName) {
        mTvTvTaskName.setText(taskName);
    }

    @Override
    public void showUploadType(boolean isVisible) {
        mLluploadType.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setUploadName(String name) {
        mtvUploadTypeValue.setText(name);
    }

    @Override
    public void showUploadPlatform(boolean isVisible) {
        mLlUploadPlatform.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setUploadPlatform(String name) {
        mTvBlePlatformValue.setText(name);
    }

    @Override
    public void showFirmwareNormal(boolean isVisible) {
        mLlFirmsareNormal.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setFirmwareNameNormal(String firmwareNormalName) {
        mTvFirmwareNormalName.setText(firmwareNormalName);
    }

    @Override
    public void setFirmwareVersionNormal(String firmwareNormalVersion) {
        mTvFirmwareNormalVersionValue.setText(firmwareNormalVersion);
    }

    @Override
    public void showBootloader(boolean isVisible) {
        mLlBootloader.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setBootloaderName(String bootloaderName) {
        mTvBootloaderValue.setText(bootloaderName);
    }

    @Override
    public void setBootloaderVersion(String bootloaderVersion) {
        mTvBootloaderVersionValue.setText(bootloaderVersion);
    }

    @Override
    public void showFirmwareSpecial(boolean isVisible) {
        mLlFirmwareSpecial.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setFirmwareNameSpecial(String firmwareNameSpecial) {
        mTvFirmwareSpecialName.setText(firmwareNameSpecial);
    }

    @Override
    public void setFirmwareVersionSpecial(String firmwareVersionSpecial) {
        mTvFirmwareSpecialversionValue.setText(firmwareVersionSpecial);
    }

    @Override
    public void showFirmwareFont(boolean isVisible) {
        mLlFirmwareFont.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setFirmwareNameFont(String firmwareNameFont) {
        mTvFirmwareFontName.setText(firmwareNameFont);
    }

    @Override
    public void setFirmwareVersionFont(String firmwareVersionFont) {
        mTvFirmwareFontVersionValue.setText(firmwareVersionFont);
    }

    @Override
    public void showFirmwareNew(boolean isVisible) {
        mLlFirmwareNew.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void setFirmwareNameNew(String firmwareNameNew) {
        mTvFirmwareNewName.setText(firmwareNameNew);
    }

    @Override
    public void setFirmwareFontVersionNew(String firmwareFontVersionNew) {
        mTvFirmwareNewVersionValue.setText(firmwareFontVersionNew);
    }

    @Override
    public void setTextBtnStartTask(String textBtnStartTask) {
        mBtnStart.setText(textBtnStartTask);
    }

    @Override
    public String getTextBtnStartTask() {
        return mBtnStart.getText().toString();
    }

    @Override
    public void showLoadingDialog() {
        WaitingDialog.showDialog(getActivity());
    }

    @Override
    public void hideLoadingDialog() {
        WaitingDialog.hideDialog();
    }

    @Override
    public void sendDeviceCount(int deviceCount) {
        mDeviceManagerModel.getDeviceCout().postValue(deviceCount);
    }

    @Override
    public void setDeviceCount(int count) {
        mTvDeviceCount.setText(String.valueOf(count));
    }

    @Override
    public void setDeviceCountColor(int color) {
        mTvDeviceCount.setTextColor(color);
    }

    @Override
    public void setVeneerCount(int count) {
        mTvVeneerCount.setText(String.valueOf(count));
    }

    @Override
    public void setVeneerColor(int color) {
        mTvVeneerCount.setTextColor(color);
    }

    @Override
    public void sendDeviceList(List<Device> deviceList) {
        IDLog.d(TAG, "sendDeviceList: " + deviceList.size());
        for(int i = 0;i < deviceList.size() ;i++){
            IDLog.d(TAG, "sendDeviceList: " + deviceList.get(i).toString());
        }
        mDeviceManagerModel.getDeviceModelLiveData().postValue(deviceList);
    }

    @Override
    public void sendVeneerList(List<Veneer> veneerList) {
        IDLog.d(TAG, "sendVeneerList: " + veneerList.size());
        mDeviceManagerModel.getVeneerModelLiveData().postValue(veneerList);
    }

    @Override
    public void startTimer() {
        mDeviceManagerModel.startTimer();
    }

    @Override
    public void stopTimer() {
        mDeviceManagerModel.stopTimer();
    }

    @Override
    public void showProgress(boolean isVisible) {
        mProgressBar.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public List<Veneer> getVeneerList() {
        return mVeneerList;
    }

    @Override
    public List<Device> getDeviceList() {
        return mDeviceList;
    }

    @Override
    public void setUpgradeCount(int count) {
        mTvUpgradeCount.setText(String.valueOf(count));
    }

    @Override
    public void setSuccessCount(int count) {
        mTvSuccessCount.setText(String.valueOf(count));
    }

    @Override
    public void setFailCount(int count) {
        if(count == 0){
            mTvFailCount.setText(String.valueOf(0));
            mTvFailCount.setTextColor(ResourceUtil.getColor(R.color.com_color_black_text));
        }else {
            mTvFailCount.setVisibility(View.VISIBLE);
            mTvFailCount.setTextColor(ResourceUtil.getColor(R.color.com_color_red));
            mTvFailCount.setText(String.valueOf(count));
        }

    }

    @Override
    public void showMessage(String message) {
        ToastUtils.show(message);
    }

    @Override
    public String getUpgrageCount() {
        return mTvUpgradeCount.getText().toString();
    }

    @Override
    public void showConfirmCancelTask() {
        WhiteConfirmDialog mWhiteConfirmDialog = WhiteConfirmDialog.newInstance(
                "是否确定取消当前升级？进度将被请零", "确定",
                "取消", true);
        mWhiteConfirmDialog.setOnConfirmListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //todo 确定取消升级
                mPresenter.stopTask(mVeneerList);
                mWhiteConfirmDialog.dismissAllowingStateLoss();
            }
        });
        mWhiteConfirmDialog.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //取消弹框
                mWhiteConfirmDialog.dismissAllowingStateLoss();
            }
        });

        mWhiteConfirmDialog.setCancelable(false);
        mWhiteConfirmDialog.show(getActivity().getSupportFragmentManager());
    }

    @Override
    public void showSearchSuccess(boolean isVisible) {
        mBtnSearchSuccess.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void showTextToTTS(String text) {
        mTextToSpeech.speak(text,
                TextToSpeech.QUEUE_FLUSH, null);
    }

    @Override
    public void setToConfig(boolean isConfig,boolean mIsUpgradeComplete) {
        if(mOnItemListener != null){
            mOnItemListener.onConfig(isConfig,mIsUpgradeComplete);
        }
    }

    @Override
    public void setDeviceId(String deviceId) {
        mTvDeviceId.setText(deviceId);
    }

    @Override
    public String getDeviceId() {
        return mTvDeviceId.getText().toString();
    }

    @Override
    public void showStartConfig(boolean isVisible) {
        mTvStartConfig.setVisibility(isVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onDestroyTask() {
        super.onDestroyTask();
    }


}
